package data.network

import data.DataLocalManager
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

// ref link:https://github.com/free-news-api/news-api
//          https://newsapi.org/
//          申请账户，然后拿到api key
object RetrofitBase {
    private const val baseUrl = "https://newsapi.org/"

    private val httpClient: OkHttpClient by lazy {
        OkHttpClient.Builder()
            .addInterceptor(Interceptor { chain ->

                val original = chain.request()
                val request = original.newBuilder()
                    .header(
                        "Authorization",
                        "Bearer ${
                            DataLocalManager.getInstance().getInfoTokenKey()
                        }"
                    )
                    .build()
                chain.proceed(request)
            }).build()
    }

    private val retrofit: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    fun <T> apiService(serviceClass: Class<T>): T {
        return retrofit.create(serviceClass)
    }

}